package com.accountant.travelaccountant;

import java.math.BigInteger;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class EditPurpose extends Activity {

	Button btnEdit, btnDelete;
	Spinner spnMembers, spnPurposes;
	TextView txtAmount;
	ArrayList<String> arrSpnMembers, arrSpnPurposes;
	ArrayAdapter<String> adapterMembers, adapterPurposes, adapter;
	DatabaseOperations_NonActivity databaseOperations;
	EditText input, input2;
	/* Alert Dialog */
	AlertDialog.Builder dialogBuilder, dialogBuilder2;
	AlertDialog alertDialog, alertDialog2;

	/* Variables for purpose and amount */
	String purpose = new String();
	BigInteger newPurposeAmount;

	/***********************************/
	/* Size for the account */
	BigInteger accountTotalSize;
	/* The amount table for amount */
	BigInteger amountTableAmount;
	/* Average for the above amount */
	BigInteger averageOfAmount;
	/* Get all the members in an arraylist */
	ArrayList<String> purposeList, memberList1;
	/* Get all the amounts paid by every member */
	ArrayList<String> memberAmounts;

	/***********************************/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_purpose);

		/* Creating an object of DatabaseOperations */
		databaseOperations = new DatabaseOperations_NonActivity(this);

		/* Initialising the Array lists and adapters */
		arrSpnMembers = new ArrayList<String>();
		arrSpnPurposes = new ArrayList<String>();
		adapterMembers = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, arrSpnMembers);
		adapterPurposes = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, arrSpnPurposes);

		/* Initialising the controls */
		btnDelete = (Button) findViewById(R.id.btnDeletePurpose);
		btnEdit = (Button) findViewById(R.id.btnEditPurpose);
		spnMembers = (Spinner) findViewById(R.id.spnMembers);
		spnPurposes = (Spinner) findViewById(R.id.spnPurposes);
		spnMembers.setAdapter(adapterMembers);
		spnPurposes.setAdapter(adapterPurposes);
		txtAmount = (TextView) findViewById(R.id.txtAmount);

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/* Retrieving all the members belonging to the particular account */
		arrSpnMembers = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity.getMembertablemember() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\"", null,
				null, null, null);
		/*
		 * Retrieving all the purposes for the first member of the array list of
		 * members so that at least the spinner is initialised. Later on we will
		 * do on event
		 */
		arrSpnPurposes = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity.getPurposetablepurpose() },
				DatabaseOperations_NonActivity.getPurposetabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\" and "
						+ DatabaseOperations_NonActivity.getPurposetablepayingmember()
						+ "=\"" + arrSpnMembers.get(0) + "\"", null, null,
				null, null);

		/* Initialising the spinners */
		adapterMembers = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, arrSpnMembers);
		adapterPurposes = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, arrSpnPurposes);
		spnMembers.setAdapter(adapterMembers);
		spnPurposes.setAdapter(adapterPurposes);

		/*
		 * Incase there are no purposes then it should not open at all and give
		 * a message that no purposes
		 */
		if (arrSpnPurposes.size() != 0) {

			/*
			 * Retrieving the amount for the very first purpose just to
			 * initialize
			 */
			String amount = databaseOperations
					.retrieve(
							DatabaseOperations_NonActivity.getPurposetable(),
							new String[] { DatabaseOperations_NonActivity
									.getPurposetableamount() },
							DatabaseOperations_NonActivity.getPurposetabletitle()
									+ "=\""
									+ SessionClass_NonActivity.sessionObject().getTitle()
									+ "\" and "
									+ DatabaseOperations_NonActivity
											.getPurposetablepayingmember()
									+ "=\""
									+ arrSpnMembers.get(0)
									+ "\" and "
									+ DatabaseOperations_NonActivity
											.getPurposetablepurpose() + "=\""
									+ arrSpnPurposes.get(0) + "\"", null, null,
							null, null);
			txtAmount.setText(amount);
		} else {
			txtAmount.setText("");
		}
		/* Closing the database */
		databaseOperations.closeDatabase();

		spnMembers.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(EditPurpose.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				/* Opening the database */
				databaseOperations.openWriteableDatabase();

				/*
				 * Retrieving all the purposes for the first member of the array
				 * list of members so that at least the spinner is initialised.
				 * Later on we will do on event
				 */
				arrSpnPurposes = databaseOperations.retrieveAll(
						DatabaseOperations_NonActivity.getPurposetable(),
						new String[] { DatabaseOperations_NonActivity
								.getPurposetablepurpose() },
						DatabaseOperations_NonActivity.getPurposetabletitle()
								+ "=\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getPurposetablepayingmember() + "=\""
								+ spnMembers.getSelectedItem().toString()
								+ "\"", null, null, null, null);
				/* Initialising the spinners */
				adapterPurposes = new ArrayAdapter<String>(
						getApplicationContext(),
						android.R.layout.simple_spinner_item, arrSpnPurposes);
				spnPurposes.setAdapter(adapterPurposes);

				/*
				 * Retrieving the amount for the very first purpose just to
				 * Initialise
				 */
				if (spnPurposes.getSelectedItem() != null) {
					String amount = databaseOperations.retrieve(
							DatabaseOperations_NonActivity.getPurposetable(),
							new String[] { DatabaseOperations_NonActivity
									.getPurposetableamount() },
							DatabaseOperations_NonActivity.getPurposetabletitle()
									+ "=\""
									+ SessionClass_NonActivity.sessionObject().getTitle()
									+ "\" and "
									+ DatabaseOperations_NonActivity
											.getPurposetablepayingmember()
									+ "=\""
									+ spnMembers.getSelectedItem().toString()
									+ "\" and "
									+ DatabaseOperations_NonActivity
											.getPurposetablepurpose() + "=\""
									+ spnPurposes.getSelectedItem().toString()
									+ "\"", null, null, null, null);
					txtAmount.setText(amount);
				} else {
					txtAmount.setText("");
				}
				/* Closing the database */
				databaseOperations.closeDatabase();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		spnPurposes.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(EditPurpose.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}

				/* Opening the database */
				databaseOperations.openWriteableDatabase();

				/*
				 * Retrieving the amount for the very first purpose just to
				 * Initialise
				 */
				String amount = databaseOperations.retrieve(
						DatabaseOperations_NonActivity.getPurposetable(),
						new String[] { DatabaseOperations_NonActivity
								.getPurposetableamount() },
						DatabaseOperations_NonActivity.getPurposetabletitle()
								+ "=\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getPurposetablepayingmember() + "=\""
								+ spnMembers.getSelectedItem().toString()
								+ "\" and "
								+ DatabaseOperations_NonActivity.getPurposetablepurpose()
								+ "=\""
								+ spnPurposes.getSelectedItem().toString()
								+ "\"", null, null, null, null);
				txtAmount.setText(amount);

				/* Closing the database */
				databaseOperations.closeDatabase();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		btnEdit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(EditPurpose.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}
				if (spnPurposes.getSelectedItem() == null) {
					Toast.makeText(getApplicationContext(),
							"No Purposes To Edit", Toast.LENGTH_SHORT).show();
					txtAmount.setText("");
					return;
				}
				showDialogBoxEditPurpose("Edit this purpose",
						"Change your purpoose here");

			}
		});

		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*
				 * Check for if the database does not exist go directly go to
				 * front screen
				 */
				if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
					Intent intent1 = new Intent(EditPurpose.this,
							FrontScreen.class);
					startActivity(intent1);
					return;
				}
				/*
				 * Case where a member has no purposes at all then we should not
				 * allow to delete
				 */
				if (spnPurposes.getSelectedItem() == null) {
					Toast.makeText(getApplicationContext(),
							"No Purpose To Delete", Toast.LENGTH_SHORT).show();
					txtAmount.setText("");
					return;
				}

				showDialogBoxDeletePurpose("Delete Member",
						"Do you want to delete "
								+ spnPurposes.getSelectedItem().toString());
			}
		});

	}

	/* Dialog box for editing a purpose amount */
	private void showDialogBoxEditPurposeAmount(String title, String message) {
		/* Creating the second dialog box */
		/* Firstly we create an object of AlertDialog.Builder */
		dialogBuilder2 = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder2.setTitle(title);
		dialogBuilder2.setMessage(message);
		/* Creating a textbox */
		input2 = new EditText(this);

		/* Setting the input type for this text box */
		input2.setInputType(InputType.TYPE_CLASS_NUMBER);

		/* Refill the textbox */
		input2.setSingleLine();

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(getApplicationContext());

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		input2.setText(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity.getPurposetableamount() },
				DatabaseOperations_NonActivity.getPurposetabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\" and "
						+ DatabaseOperations_NonActivity.getPurposetablepayingmember()
						+ "=\"" + spnMembers.getSelectedItem().toString()
						+ "\" and "
						+ DatabaseOperations_NonActivity.getPurposetablepurpose() + "=\""
						+ spnPurposes.getSelectedItem().toString() + "\"",
				null, null, null, null));

		/* Fucntion to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input2);

		/* Close the database */
		databaseOperations.closeDatabase();

		dialogBuilder2.setView(input2);

		input2.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateNumberTextLength(input2);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder2.setPositiveButton("Change",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						/*
						 * Suppose nothing entered in to the text box and
						 * whatever was there was deleted then it means nothing
						 * i.e 0
						 */
						if (input2.getText().length() == 0)
							newPurposeAmount = new BigInteger("0");
						else
							/* Getting the amount */
							newPurposeAmount = new BigInteger( input2
									.getText().toString());
						/*
						 * If the amount is invalid say negative then do not
						 * accept it
						 */
						if (newPurposeAmount.intValue() < 0) {
							Toast.makeText(getApplicationContext(),
									"The amount entered is invalid",
									Toast.LENGTH_SHORT).show();
							return;
						}

						/* Opening the database */
						databaseOperations.openWriteableDatabase();

						/*
						 * Getting the purpose amount from the purpose table for
						 * that record you are trying to delete
						 */
						BigInteger oldPurposeAmount = new BigInteger(databaseOperations.retrieve(
								DatabaseOperations_NonActivity.getPurposetable(),
								new String[] { DatabaseOperations_NonActivity
										.getPurposetableamount() },
								DatabaseOperations_NonActivity.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity.sessionObject()
												.getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\""
										+ spnMembers.getSelectedItem()
												.toString()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepurpose()
										+ "=\""
										+ spnPurposes.getSelectedItem()
												.toString() + "\"", null, null,
								null, null));

						/* Getting the total amount for that title */
						BigInteger oldMemberAmount =new BigInteger(databaseOperations.retrieve(
										DatabaseOperations_NonActivity.getMembertable(),
										new String[] { DatabaseOperations_NonActivity
												.getMembertableamount() },
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\""
												+ spnMembers.getSelectedItem()
														.toString() + "\"",
										null, null, null, null));

						/* Getting the total amount for that title */
						BigInteger oldTotalAmount = new BigInteger(databaseOperations.retrieve(
										DatabaseOperations_NonActivity.getAmounttable(),
										new String[] { DatabaseOperations_NonActivity
												.getAmounttableamount() },
										DatabaseOperations_NonActivity
												.getAmounttabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle() + "\"",
										null, null, null, null));

						if (newPurposeAmount.intValue() < oldPurposeAmount.intValue()) {
							if (oldMemberAmount.intValue()
									- (oldPurposeAmount.intValue() - newPurposeAmount.intValue()) < 0
									|| oldTotalAmount.intValue()
											- (oldPurposeAmount.intValue() - newPurposeAmount.intValue()) < 0) {
								Toast.makeText(getApplicationContext(),
										"Amount Entered must be invalid",
										Toast.LENGTH_SHORT).show();
								return;
							} else {
								/* Update the purpose table purposes and amounts */
								databaseOperations.updateMoreThanOneColumn(
										DatabaseOperations_NonActivity.getPurposetable(),
										new String[] {
												DatabaseOperations_NonActivity
														.getPurposetablepurpose(),
												DatabaseOperations_NonActivity
														.getPurposetableamount() },
										new String[] {
												purpose,
												String.valueOf(newPurposeAmount.intValue()) },
										DatabaseOperations_NonActivity
												.getPurposetabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepayingmember()
												+ "=\""
												+ spnMembers.getSelectedItem()
														.toString()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepurpose()
												+ "=\""
												+ spnPurposes.getSelectedItem()
														.toString() + "\"",
										null);

								/*
								 * Updating the amount in the member table
								 * because a purpose has been deleted
								 */
								databaseOperations.updateRow(
										DatabaseOperations_NonActivity.getMembertable(),
										DatabaseOperations_NonActivity
												.getMembertableamount(),
										String.valueOf(oldMemberAmount.intValue()
												- (oldPurposeAmount.intValue() - newPurposeAmount.intValue())),
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\""
												+ spnMembers.getSelectedItem()
														.toString() + "\"",
										null);

								/*
								 * Updating the amount in the amount table
								 * because a purpose has been deleted
								 */
								databaseOperations.updateRow(
										DatabaseOperations_NonActivity.getAmounttable(),
										DatabaseOperations_NonActivity
												.getAmounttableamount(),
										String.valueOf(oldTotalAmount.intValue()
												- (oldPurposeAmount.intValue() - newPurposeAmount.intValue())),
										DatabaseOperations_NonActivity
												.getAmounttabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle() + "\" ",
										null);

							}
						} else {
							/* Update the purpose table purposes and amounts */
							databaseOperations.updateMoreThanOneColumn(
									DatabaseOperations_NonActivity.getPurposetable(),
									new String[] {
											DatabaseOperations_NonActivity
													.getPurposetablepurpose(),
											DatabaseOperations_NonActivity
													.getPurposetableamount() },
									new String[] { purpose,
											String.valueOf(newPurposeAmount.intValue()) },
									DatabaseOperations_NonActivity.getPurposetabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepayingmember()
											+ "=\""
											+ spnMembers.getSelectedItem()
													.toString()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepurpose()
											+ "=\""
											+ spnPurposes.getSelectedItem()
													.toString() + "\"", null);

							/*
							 * Updating the amount in the member table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity.getMembertable(),
									DatabaseOperations_NonActivity.getMembertableamount(),
									String.valueOf(oldMemberAmount.intValue()
											+ newPurposeAmount.intValue()
											- oldPurposeAmount.intValue()),
									DatabaseOperations_NonActivity.getMembertabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getMembertablemember()
											+ "=\""
											+ spnMembers.getSelectedItem()
													.toString() + "\"", null);

							/*
							 * Updating the amount in the amount table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity.getAmounttable(),
									DatabaseOperations_NonActivity.getAmounttableamount(),
									String.valueOf(oldTotalAmount.intValue()
											+ newPurposeAmount.intValue()
											- oldPurposeAmount.intValue()),
									DatabaseOperations_NonActivity.getAmounttabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle() + "\" ", null);
						}

						/*
						 * Getting the list of all purposes and assigning to the
						 * spinner because after deleting the member we need to
						 * update
						 */
						purposeList = databaseOperations.retrieveAll(
								DatabaseOperations_NonActivity.getPurposetable(),
								new String[] { DatabaseOperations_NonActivity
										.getPurposetablepurpose() },
								DatabaseOperations_NonActivity.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity.sessionObject()
												.getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\""
										+ spnMembers.getSelectedItem()
												.toString() + "\"", null, null,
								null, null);
						adapter = new ArrayAdapter<String>(
								getApplicationContext(),
								android.R.layout.simple_spinner_item,
								purposeList);
						spnPurposes.setAdapter(adapter);

						/*
						 * Updating the member table by calling the function of
						 * purpose class
						 */
						updateToGetAndToGiveColumns();

						/* Code to close the database */
						databaseOperations.closeDatabase();

					}
				});

		dialogBuilder2.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		alertDialog2 = dialogBuilder2.create();
		alertDialog2.show();
	}

	/* Dialog box for editing a purpose */
	private void showDialogBoxEditPurpose(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(getApplicationContext());

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/* Firstly we create an object of AlertDialog.Builder */
		dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		/* Creating a textbox */
		input = new EditText(this);
		input.setSingleLine();
		/* The purpose should be already there whatever is selected */
		input.setText(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity.getPurposetablepurpose() },
				DatabaseOperations_NonActivity.getPurposetabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\" and "
						+ DatabaseOperations_NonActivity.getPurposetablepayingmember()
						+ "=\"" + spnMembers.getSelectedItem().toString()
						+ "\" and "
						+ DatabaseOperations_NonActivity.getPurposetablepurpose() + "=\""
						+ spnPurposes.getSelectedItem().toString() + "\"",
				null, null, null, null));

		/* Function to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input);

		/* Getting the purpose */
		purpose = input.getText().toString();

		/* Close the database */
		databaseOperations.closeDatabase();

		/* Assigning that text field to dialogBuilder */
		dialogBuilder.setView(input);

		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Change",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (input.getText().toString().replaceAll("\\s+", " ")
								.trim().length() != 0) {
							/* Opening the database */
							databaseOperations.openWriteableDatabase();
							/* Getting the purpose */
							purpose = input.getText().toString()
									.replaceAll("\\s+", " ").trim();

							/* Closing the database */
							databaseOperations.closeDatabase();

							showDialogBoxEditPurposeAmount("Edit this amount",
									"Enter the new amount");
						} else {
							Toast.makeText(getApplicationContext(),
									"Purpose cannot be blank",
									Toast.LENGTH_SHORT).show();
							dialog.dismiss();
						}
					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for Deleting a purpose */
	private void showDialogBoxDeletePurpose(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(getApplicationContext());

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);
		dialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* Code to open the database */
						databaseOperations.openWriteableDatabase();

						/*
						 * Getting the purpose amount from the purpose table for
						 * that record you are trying to delete
						 */
						BigInteger purposeAmount =new BigInteger(databaseOperations.retrieve(
								DatabaseOperations_NonActivity.getPurposetable(),
								new String[] { DatabaseOperations_NonActivity
										.getPurposetableamount() },
								DatabaseOperations_NonActivity.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity.sessionObject()
												.getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\""
										+ spnMembers.getSelectedItem()
												.toString()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepurpose()
										+ "=\""
										+ spnPurposes.getSelectedItem()
												.toString() + "\"", null, null,
								null, null));

						/* Getting the total amount for that title */
						BigInteger memberAmount =new BigInteger(databaseOperations
								.retrieve(
										DatabaseOperations_NonActivity.getMembertable(),
										new String[] { DatabaseOperations_NonActivity
												.getMembertableamount() },
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\""
												+ spnMembers.getSelectedItem()
														.toString() + "\"",
										null, null, null, null));

						/*
						 * Deleting the particular records by going to the
						 * title->member->purpose
						 */
						if (databaseOperations.deleteRow(
								DatabaseOperations_NonActivity.getPurposetable(),
								DatabaseOperations_NonActivity.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity.sessionObject()
												.getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\""
										+ spnMembers.getSelectedItem()
												.toString()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepurpose()
										+ "=\""
										+ spnPurposes.getSelectedItem()
												.toString() + "\"", null) != 0) {

							/*
							 * Updating the amount in the member table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity.getMembertable(),
									DatabaseOperations_NonActivity.getMembertableamount(),
									String.valueOf(memberAmount.intValue() - purposeAmount.intValue()),
									DatabaseOperations_NonActivity.getMembertabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getMembertablemember()
											+ "=\""
											+ spnMembers.getSelectedItem()
													.toString() + "\"", null);

							/* Updating the amount in the amount table */
							/* Getting the total amount for that title */
							BigInteger totalAmount =new BigInteger(databaseOperations.retrieve(
									DatabaseOperations_NonActivity.getAmounttable(),
									new String[] { DatabaseOperations_NonActivity
											.getAmounttableamount() },
									DatabaseOperations_NonActivity.getAmounttabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle() + "\"", null,
									null, null, null));

							/*
							 * Updating the amount in the amount table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity.getAmounttable(),
									DatabaseOperations_NonActivity.getAmounttableamount(),
									String.valueOf(totalAmount.intValue() - purposeAmount.intValue()),
									DatabaseOperations_NonActivity.getAmounttabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle() + "\" ", null);

							/*
							 * Getting the list of all purposes and assigning to
							 * the spinner because after deleting the member we
							 * need to update
							 */
							purposeList = databaseOperations.retrieveAll(
									DatabaseOperations_NonActivity.getPurposetable(),
									new String[] { DatabaseOperations_NonActivity
											.getPurposetablepurpose() },
									DatabaseOperations_NonActivity.getPurposetabletitle()
											+ "=\""
											+ SessionClass_NonActivity.sessionObject()
													.getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepayingmember()
											+ "=\""
											+ spnMembers.getSelectedItem()
													.toString() + "\"", null,
									null, null, null);
							adapter = new ArrayAdapter<String>(
									getApplicationContext(),
									android.R.layout.simple_spinner_item,
									purposeList);
							spnPurposes.setAdapter(adapter);

							if (purposeList.size() == 0) {
								txtAmount.setText("");
							}

							/*
							 * Updating the member table by calling the function
							 * of purpose class
							 */
							updateToGetAndToGiveColumns();

							/* Code to close the database */
							databaseOperations.closeDatabase();
							return;
						}

					}
				});

		dialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* After deleting a purpose again we need to update the member table */
	public void updateToGetAndToGiveColumns() {
		/* Retrieve the size of the Amount Table */
		accountTotalSize =new BigInteger(databaseOperations.retrieve(DatabaseOperations_NonActivity
						.getAmounttable(), new String[] { DatabaseOperations_NonActivity
						.getAmounttabletotalmembers() },
						DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\"", null, null, null, null));

		/*
		 * Incase all the members have been deleted then this function should
		 * not be allowed to proceed further
		 */
		if (accountTotalSize.intValue() == 0)
			return;
		/* Retrieve the amount table amount */
		amountTableAmount =new BigInteger(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity.getAmounttableamount() },
				DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\"", null,
				null, null, null));
		/* Calculating the average */
		averageOfAmount = amountTableAmount.divide(accountTotalSize);

		/* Retrieving all the members of the particular account */
		memberList1 = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity.getMembertablemember() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\"", null,
				null, null, null);

		/* Retrieving all the amounts of the particular accounts */
		memberAmounts = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity.getMembertableamount() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle() + "\"", null,
				null, null, null);

		for (int i = 0; i < accountTotalSize.intValue(); i++) {
			/*
			 * Suppose a person has given more then he has to receive from his
			 * friends
			 */
			if ((new BigInteger(memberAmounts.get(i))).intValue() >= averageOfAmount.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf( (new BigInteger(memberAmounts.get(i))).intValue()
								- averageOfAmount.intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle() + "=" + "\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity.getMembertablemember()
								+ "=" + "\"" + memberList1.get(i) + "\"", null);

				/* Making the to give columns */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle() + "=" + "\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity.getMembertablemember()
								+ "=" + "\"" + memberList1.get(i) + "\"", null);
			}
			/*
			 * Suppose a person has given less then he has to give to his
			 * friends
			 */
			else if ((new BigInteger(memberAmounts.get(i))).intValue() < averageOfAmount.intValue()) {
				/* Updating the to give column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(averageOfAmount.intValue()
								- (new BigInteger(memberAmounts.get(i))).intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle() + "=" + "\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity.getMembertablemember()
								+ "=" + "\"" + memberList1.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle() + "=" + "\""
								+ SessionClass_NonActivity.sessionObject().getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity.getMembertablemember()
								+ "=" + "\"" + memberList1.get(i) + "\"", null);
			}
		}
	}

}
